
<template>
  <div class="mapSelect">
    <el-dialog :title="title" v-dialogDrag width="80%" :visible.sync="isShow" @close="cancel"
               :close-on-click-model="false" top="1vh" :modal-append-to-body='false' style="left: 8px;top: 8%">
      <el-form :model="form" :label-position="'left'" size="mini" ref="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地址" :label-width="'72px'" prop="address">
              <div class="tips-box">
                <el-input class="map-input" id="pickerInput1"
                          placeholder="请输入并选择地址" v-model="form.address" @change="clearAddressInfo"></el-input>
              </div>
              <span class="map-tips">如果填写了地址并且选定后地图中定位到的蓝色图标不够精确，可拖动地图精确定位！</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
        <div id="container" class="map" tabindex="0"></div>
        </el-row>
      </el-form>
      <div style="text-align: right;margin-top: 8px">
        <el-button size="mini" @click="cancel">取 消</el-button>
        <el-button type="primary" size="mini" @click="operation">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import AMap from 'AMap'
  import AMapUI from 'AMapUI'

  export default {
    name: 'operation',
    props: ['showOperation', 'formData','matchData'],
    data () {
      return {
        isShow: this.showOperation,
        title: '选择地址',
        form: {
          mapAddress: this.formData.mapAddress || '',
          subAddress: this.formData.subAddress || '',
          address: this.formData.address || '',
          adcode: this.formData.adcode || '',
          lngX: this.formData.lngX || '',
          latY: this.formData.latY || ''
        },
        match: {},
        rules: {
          address: [
            {required: true, validator: '请填写地址后定位到地图中', trigger: 'blur,change'}
          ]
        }
      }
    },
    methods: {
      clearAddressInfo () {
        this.form.subAddress = ''
        this.form.address = ''
        this.form.lngX = ''
        this.form.latY = ''
        this.form.adcode = ''
      },
      cancel: function () {
        this.isShow = false
        this.$emit('update:showOperation', this.isShow)
      },
      loadMap: function () {
        let self = this
        self.map = new AMap.Map('container', {
          center: self.matchData != null && (self.matchData.lngX == '' || self.matchData.lngX == null) ? false : [self.matchData.lngX,this.matchData.latY],
          zoom: 32,
          scrollWheel: true,
          resizeEnable: true
        })

        AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
          let poiPicker = new PoiPicker({
            city: self.matchData.adcode,
            citylimit: true,
            input: 'pickerInput1'
          })
          poiPicker.on('poiPicked', function (poiResult) {
            let item = poiResult.item
            if (item.location) {
              let location = item.location
              let position = [location.lng, location.lat]
              self.positionPicker(position, item.adcode, item.name)
            } else {
              self.form.mapAddress = ''
              self.$message({
                message: '请输入带有经纬度的地址',
                type: 'warning'
              })
            }
          })
        })
        //self.map.on('click', self.getClickPosition);
      },
      positionPicker (position, adcode, name) {
        let self = this
        AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {
          let positionPicker = new PositionPicker({
            mode: 'dragMap',
            map: self.map
          })
          positionPicker.on('success', function (positionResult) {
            self.form.address = positionResult.address
            let position = positionResult.position
            self.form.lngX = position.lng
            self.form.latY = position.lat
            self.form.adcode = adcode
            debugger
            if (positionResult.regeocode) {
              let addressComponent = positionResult.regeocode.addressComponent
              if (addressComponent) {
                self.form.city = addressComponent.city
                self.form.province = addressComponent.province
                self.form.district = addressComponent.district
                if (!self.form.adcode) {
                  self.form.adcode = addressComponent.adcode
                }
              }
            }
            var placeSearch = new AMap.PlaceSearch({
              city: self.form.adcode
            })
            placeSearch.searchNearBy(name, [positionResult.position.lng, positionResult.position.lat], 200, function (status, result) {
              if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
                self.form.mapAddress = result.poiList.pois[0].name
                if(result.poiList.pois[0].address){
                  self.form.subAddress = result.poiList.pois[0].address
                }else{
                  self.form.subAddress = result.poiList.pois[0].name
                }
              } else {
                self.form.mapAddress = positionResult.regeocode.pois[0].name
                self.form.subAddress = positionResult.regeocode.pois[0].address
              }
            })
          })
          positionPicker.on('fail', function (positionResult) {
            console.log('获取地址失败!')
            console.log(positionResult)
          })
          positionPicker.start(position)
        })
      },
      operation: function () {
        let self = this
        self.$refs['form'].validate(function (valid) {
          if (valid) {
            self.$emit('confirm', self.form)
            self.cancel()
          }
        })
      },
      getClickPosition(e){
        let position = [e.lnglat.getLng(), e.lnglat.getLat()]
        console.log('=============',e)
        this.positionPicker(position)
      }
    },
    mounted: function () {
      let self = this
      this.$nextTick(function () {
        self.loadMap()
        if (self.matchData && self.matchData.lngX) {
          self.positionPicker([self.matchData.lngX, self.matchData.latY])
        }
        if (self.positionPicker && self.form.lngX && self.form.latY) {
          self.positionPicker([self.form.lngX, self.form.latY])
        }
      })
    }
  }
</script>
<style scoped>
  .map-tips {
    font-size: 13px;
    color: #5cabf9;
  }

  .tips-box {
    display: flex;
    flex-direction: row;
    justify-items: center;
  }

  .map-input {
    width: 500px;
  }

  .tips-box span {
    margin-left: 9px;
  }

  #container {
    width: 100%;
    height: 500px;
    margin: 0;
    font-size: 13px;
  }
</style>
